package com.zpark.wxshop.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zpark.wxshop.Utils.Result;
import com.zpark.wxshop.Utils.redisUtil;

import com.zpark.wxshop.service.IUserService;
import com.zpark.wxshop.entity.User;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author PJone
 * @since 2023-09-04
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private redisUtil redisUtil;

    /**
    * 新增与修改
    */
    @PostMapping
    public Result save(@RequestBody User user) {
        userService.saveOrUpdate(user);
        return Result.success();
    }

    /**
    * 根据id删除
    */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.success();
    }

    /**
    * 批量删除
    */
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        userService.removeByIds(ids);
        return Result.success();
    }

    /**
    * 查询所有
    */
    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
    }

    /**
    * 根据id查询单个
    */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    /**
    * 分页查询
    */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(userService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 用户注册
     */
    @PostMapping("/reg")
    public Result Reg(@RequestBody User user){
        User user1 = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (user1 != null)
            Result.error(201, "注册失败，用户名已存在!");
        user.setCreatedTime(new Timestamp(new Date().getTime()));
        user.setCreatedUser(user.getUsername());
        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Passowrd = getMd5Password(user.getPassword(), salt);
        user.setPassword(md5Passowrd);
        user.setSalt(salt);
        userService.save(user);
        return Result.success(user);
    }

    /**
     * 用户登录
     */
    @GetMapping("/login")
    @Cacheable(cacheNames = "userlogin:#60", key = "#username")
    public Result Login(@RequestParam("username") String username, @RequestParam("password") String password){
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null){
            return Result.error(202, "没有该用户信息!!!");
        }
        String md5password = getMd5Password(password, user.getSalt());
        if (!md5password.equals(user.getPassword()))
            return Result.error(203, "密码错误");

        redisUtil.set("userInfo", user);
        return Result.success(user);
    }

    /**
     * 执行密码加密
     */
    private String getMd5Password(String password, String salt){
        /**
         * 加密规则：
         * 1.无视原始密码的强度
         * 2.使用UUID作为盐值，在原始密码的左右侧拼接
         * 3.循环加密三次然后转为Byte[]
         */
        for (int i = 0; i < 3; i++){
            //DigestUtils.md5DigestAsHex(btye[]) -- md5专属的加密算法 传入byte[]类型
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }


    /**
     * 获取redis中存储的用户信息
     */
    @GetMapping("userInfo")
    public Result ShowUserInfo(){
        User user = (User) redisUtil.get("userInfo");
        return Result.success(user);
    }

}

